#include "client.h"
#include "ui_client.h"
#include <QMessageBox>
#include "loginset.h"

client::client(QString name, QString pass, QString SERVER, QString PORT,QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::client)
{
    ui->setupUi(this);
    this->name = name;
    this->pass = pass;

    mysql.SERVER = SERVER;
    mysql.PORT = PORT;

    if(!mysql.connectMysql())
    {
        qDebug() << "数据库连接失败" << mysql.db.lastError().text();
        QMessageBox::critical(this,"连接失败","数据库连接失败，请检查IP和端口号是否正确");
    }

    // 创建模型
    memberModel = new QSqlTableModel(this, mysql.db);
    kdcModel = new QSqlTableModel(this, mysql.db);
    // 设置列宽拉伸填充表格
    ui->memberTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->kdcTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->meTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);


    // 设置为不可编辑
    ui->kdcTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->memberTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->meTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 参数化查询
    SQL = "SELECT client_contact, client_grade FROM member_info "
          "WHERE client_name = :name";
    QSqlQuery query;
    query.prepare(SQL);
    query.bindValue(":name", this->name);

    // 执行查询
    if (!query.exec()) {
        qDebug() << "查询失败：" << query.lastError().text();
        QMessageBox::critical(nullptr, "错误", "数据加载失败: " + kdcModel->lastError().text());
    }
    query.next();
    // 获取数据
    contact = query.value("client_contact").toString();
    vip = query.value("client_grade").toString();
    qDebug() << "加载：" << contact << " " << vip;
    // 更新UI
    ui->clientTxt->setText(this->name);
    ui->contactTxt->setText(this->contact);
    ui->vipTxt->setText(this->vip);
}


client::~client()
{
    delete kdcModel;
    delete memberModel;
    delete ui;
}

// 页面切换
void client::on_toolBox_currentChanged(int index)
{
    ui->stackedWidget->setCurrentIndex(index);
}

// 设置
void client::on_clientSet_clicked()
{
    loginSet *L = new loginSet(this->mysql.SERVER,this->mysql.PORT,this); // 指定父对象
    L->show();
}

// 查询所有
void client::on_all_clicked()
{
    // 创建并配置模型
    kdcModel->setTable("kdc_info"); // 绑定到你的表名
    kdcModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置字段显示名称（与实际字段名无关，仅UI显示）
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_color"), Qt::Horizontal, "车辆颜色");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_type"), Qt::Horizontal, "车辆类型");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_booking"), Qt::Horizontal, "使用状况");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_state"), Qt::Horizontal, "车辆状态");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_id"), Qt::Horizontal, "车辆编号");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_exclusive"), Qt::Horizontal, "是否专属");

    // 设置筛选条件
    // 合并条件，注意字符串值用单引号包裹
    kdcModel->setFilter("kdc_exclusive = '非专属' AND kdc_state = '完好' AND kdc_booking = '空闲'");

    error = kdcModel->lastError();

    if(!kdcModel->select()) { // 必须显式加载数据[2](@ref)
        QMessageBox::critical(nullptr, "错误", "数据加载失败: " + kdcModel->lastError().text());
        return;
    }

    // 将模型设置给kdcTableView
    ui->kdcTableView->setModel(kdcModel);
}

// 筛选双人车型
void client::on_twoPerson_clicked()
{
    // 创建并配置模型
    kdcModel->setTable("kdc_info"); // 绑定到你的表名
    kdcModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置字段显示名称（与实际字段名无关，仅UI显示）
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_color"), Qt::Horizontal, "车辆颜色");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_type"), Qt::Horizontal, "车辆类型");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_booking"), Qt::Horizontal, "使用状况");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_state"), Qt::Horizontal, "车辆状态");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_id"), Qt::Horizontal, "车辆编号");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_exclusive"), Qt::Horizontal, "是否专属");

    // 设置筛选条件
    // 合并条件，注意字符串值用单引号包裹
    kdcModel->setFilter("kdc_exclusive = '非专属' AND kdc_state = '完好' AND kdc_booking = '空闲' AND kdc_type = '双人'");

    error = kdcModel->lastError();

    if(!kdcModel->select()) { // 必须显式加载数据[2](@ref)
        QMessageBox::critical(nullptr, "错误", "数据加载失败: " + kdcModel->lastError().text());
        return;
    }

    // 将模型设置给userTableView
    ui->kdcTableView->setModel(kdcModel);
}

// 筛选单人车型
void client::on_single_clicked()
{
    // 创建并配置模型
    kdcModel->setTable("kdc_info"); // 绑定到你的表名
    kdcModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置字段显示名称（与实际字段名无关，仅UI显示）
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_color"), Qt::Horizontal, "车辆颜色");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_type"), Qt::Horizontal, "车辆类型");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_booking"), Qt::Horizontal, "使用状况");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_state"), Qt::Horizontal, "车辆状态");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_id"), Qt::Horizontal, "车辆编号");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_exclusive"), Qt::Horizontal, "是否专属");

    // 设置筛选条件
    // 合并条件，注意字符串值用单引号包裹
    kdcModel->setFilter("kdc_exclusive = '非专属' AND kdc_state = '完好' AND kdc_booking = '空闲' AND kdc_type = '成人'");


    error = kdcModel->lastError();

    if(!kdcModel->select()) { // 必须显式加载数据[2](@ref)
        QMessageBox::critical(nullptr, "错误", "数据加载失败: " + kdcModel->lastError().text());
        return;
    }

    // 将模型设置给userTableView
    ui->kdcTableView->setModel(kdcModel);
}

// 筛选儿童车型
void client::on_child_clicked()
{
    // 创建并配置模型
    kdcModel->setTable("kdc_info"); // 绑定到你的表名
    kdcModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置字段显示名称（与实际字段名无关，仅UI显示）
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_color"), Qt::Horizontal, "车辆颜色");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_type"), Qt::Horizontal, "车辆类型");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_booking"), Qt::Horizontal, "使用状况");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_state"), Qt::Horizontal, "车辆状态");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_id"), Qt::Horizontal, "车辆编号");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_exclusive"), Qt::Horizontal, "是否专属");

    // 设置筛选条件
    // 合并条件，注意字符串值用单引号包裹
    kdcModel->setFilter("kdc_exclusive = '非专属' AND kdc_state = '完好' AND kdc_booking = '空闲' AND kdc_type = '儿童'");

    error = kdcModel->lastError();

    if(!kdcModel->select()) { // 必须显式加载数据[2](@ref)
        QMessageBox::critical(nullptr, "错误", "数据加载失败: " + kdcModel->lastError().text());
        return;
    }

    // 将模型设置给kdcTableView
    ui->kdcTableView->setModel(kdcModel);
}


void client::on_me_clicked()
{
    SQL = QString("select grade AS 等级, booking AS 预约, exclusive AS 专属, car_stickers AS 车贴 FROM member where  grade = (select client_grade from member_info where client_name = %1);").arg(name);

    memberModel->setQuery(SQL, mysql.db);


    error = memberModel->lastError();
    if (error.type() != QSqlError::NoError) {
        qDebug() << "查询执行失败，错误信息: " << error.text();
        QMessageBox::critical(this,"连接失败","数据库连接失败，请检查ip地址和端口号");
    }

    // 将模型设置给userTableView
    ui->memberTableView->setModel(memberModel);
}

// 查询所有
void client::on_allVip_clicked()
{
    // 创建并配置模型
    memberModel->setTable("member"); // 绑定到你的表名

    // 设置字段显示名称（与实际字段名无关，仅UI显示）
    memberModel->setHeaderData(memberModel->fieldIndex("grade"), Qt::Horizontal, "会员等级");
    memberModel->setHeaderData(memberModel->fieldIndex("booking"), Qt::Horizontal, "预约");
    memberModel->setHeaderData(memberModel->fieldIndex("exclusive"), Qt::Horizontal, "专属");
    memberModel->setHeaderData(memberModel->fieldIndex("car_stickers"), Qt::Horizontal, "车贴");

    error = memberModel->lastError();

    if(!memberModel->select()) { // 必须显式加载数据[2](@ref)
        QMessageBox::critical(nullptr, "错误", "数据加载失败: " + memberModel->lastError().text());
        return;
    }

    // 将模型设置给userTableView
    ui->memberTableView->setModel(memberModel);
}


void client::on_bookingYes_clicked()
{
    QString kdc_id = ui->bookingTxt->text();
    QString sql = "SELECT 1 FROM kdc_info "
                  "WHERE kdc_id = :kdc_id "
                  "  AND kdc_booking = '空闲' "
                  "  AND kdc_state = '完好' "
                  "  AND kdc_exclusive = '非专属' "
                  "LIMIT 1";  // 使用LIMIT 1提升性能[1](@ref)

    QSqlQuery query;
    query.prepare(sql);  // 预编译语句[2](@ref)
    query.bindValue(":kdc_id", kdc_id);  // 绑定参数防止注入[2](@ref)

    if (!query.exec()) {
        qDebug() << "查询失败：" << query.lastError().text();  // 执行异常处理[2](@ref)
        return;
    }

    bool hasData = query.next();  // 存在数据时返回true[1,2](@ref)
    if (hasData) {

        qDebug() << "存在符合条件的记录";
        sql = "UPDATE kdc_info SET kdc_booking = :name WHERE kdc_id = :kdc_id LIMIT 1";
        query.prepare(sql);  // 预编译语句[2](@ref)
        query.bindValue(":kdc_id", kdc_id.toInt());  // 绑定参数防止注入[2](@ref)
        query.bindValue(":name", name);
        if (!query.exec()) {
            qDebug() << "更新失败" << query.lastError().text();  // 执行异常处理[2](@ref)
            QMessageBox::critical(nullptr, "预约提示", "预约失败: " + memberModel->lastError().text());
            return;
        }
        // 信息提示框（带感叹号图标）
        QMessageBox::information(nullptr, "预约提示", "预约成功", QMessageBox::Ok);

    } else {
        QMessageBox::critical(nullptr, "预约提示", "该车不存在或不可使用: " + memberModel->lastError().text());
    }
}


void client::on_clientTxtYes_clicked()
{
    QString old = name;
    name = ui->clientTxt->text();

    // 参数化查询
    SQL = "UPDATE user SET "
          "uname = :name "
          "WHERE uname = :old";
    QSqlQuery query;
    query.prepare(SQL);
    query.bindValue(":name", name);
    query.bindValue(":old", old);

    if(!query.exec())
    {
        qDebug() << "更新失败：" << query.lastError().text();
        QMessageBox::warning(this,"修改失败","修改失败,用户名已存在");
        ui->clientTxt->setText(old);
        name =  old;
    }
    else
    {
        qDebug() << "更新成功，影响行数：" << query.numRowsAffected();
        QMessageBox::information(this,"更新成功","更新成功");
        ui->clientTxt->setText(name);
    }
}


void client::on_contactTxtYes_clicked()
{
    QString old = contact;
    contact = ui->contactTxt->text();
    // 参数化查询
    SQL = "UPDATE member_info SET "
          "client_contact = :contact "
          "WHERE client_name = :name";
    QSqlQuery query;
    query.prepare(SQL);
    query.bindValue(":name", name);
    query.bindValue(":contact", contact);
    if(!query.exec())
    {
        qDebug() << "更新失败：" << query.lastError().text();
        QMessageBox::warning(this,"修改失败","更新成功");
        ui->contactTxt->setText(old);
        contact = old;
    }
    else
    {
        qDebug() << "更新成功，影响行数：" << query.numRowsAffected();
        QMessageBox::information(this,"更新成功","更新成功");
        ui->contactTxt->setText(contact);
    }
}


void client::on_bookingSelect_clicked()
{
    int linex = 0;
    ui->stackedWidget->setCurrentIndex(linex);
    // 创建并配置模型
    kdcModel->setTable("kdc_info"); // 绑定到你的表名
    kdcModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置字段显示名称（与实际字段名无关，仅UI显示）
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_color"), Qt::Horizontal, "车辆颜色");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_type"), Qt::Horizontal, "车辆类型");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_booking"), Qt::Horizontal, "使用状况");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_state"), Qt::Horizontal, "车辆状态");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_id"), Qt::Horizontal, "车辆编号");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_exclusive"), Qt::Horizontal, "是否专属");

    // 设置筛选条件
    // 合并条件，注意字符串值用单引号包裹
    SQL = QString(" kdc_booking = %1").arg(name);
    kdcModel->setFilter(SQL);


    error = kdcModel->lastError();

    if(!kdcModel->select()) { // 必须显式加载数据[2](@ref)
        QMessageBox::critical(nullptr, "错误", "数据加载失败: " + kdcModel->lastError().text());
        return;
    }

    // 将模型设置给kdcTableView
    ui->kdcTableView->setModel(kdcModel);
}


void client::on_selectExclBooking_clicked()
{
    // 创建并配置模型
    kdcModel->setTable("kdc_info"); // 绑定到你的表名
    kdcModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置字段显示名称（与实际字段名无关，仅UI显示）
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_color"), Qt::Horizontal, "车辆颜色");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_type"), Qt::Horizontal, "车辆类型");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_booking"), Qt::Horizontal, "使用状况");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_state"), Qt::Horizontal, "车辆状态");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_id"), Qt::Horizontal, "车辆编号");
    kdcModel->setHeaderData(kdcModel->fieldIndex("kdc_exclusive"), Qt::Horizontal, "是否专属");

    // 设置筛选条件
    // 合并条件，注意字符串值用单引号包裹
    SQL = QString(" kdc_booking = %1 OR kdc_exclusive = %1").arg(name);
    kdcModel->setFilter(SQL);


    error = kdcModel->lastError();

    if(!kdcModel->select()) { // 必须显式加载数据[2](@ref)
        QMessageBox::critical(nullptr, "错误", "数据加载失败: " + kdcModel->lastError().text());
        return;
    }

    // 将模型设置给meTableView
    ui->meTableView->setModel(kdcModel);
}


void client::on_exclusiveTxtYes_clicked()
{
    QString kdc_id = ui->exclusiveTxt->text();

    if(vip == "VIP1")
    {
        QMessageBox::critical(nullptr, "错误", "只有VIP2及以上才可以申请专属车辆: ");
        return;
    }

    QString sql = "SELECT 1 FROM kdc_info "
                  "WHERE kdc_id = :kdc_id "
                  "  AND kdc_booking = '空闲' "
                  "  AND kdc_state = '完好' "
                  "  AND kdc_exclusive = '非专属' "
                  "LIMIT 1";  // 使用LIMIT 1提升性能[1](@ref)

    QSqlQuery query;
    query.prepare(sql);  // 预编译语句[2](@ref)
    query.bindValue(":kdc_id", kdc_id);  // 绑定参数防止注入[2](@ref)

    if (!query.exec()) {
        qDebug() << "查询失败：" << query.lastError().text();  // 执行异常处理[2](@ref)
        return;
    }

    bool hasData = query.next();  // 存在数据时返回true[1,2](@ref)
    if (hasData) {

        qDebug() << "存在符合条件的记录";
        sql = "UPDATE kdc_info SET kdc_exclusive = :name WHERE kdc_id = :kdc_id ";
        query.prepare(sql);  // 预编译语句[2](@ref)
        query.bindValue(":kdc_id", kdc_id.toInt());  // 绑定参数防止注入[2](@ref)
        query.bindValue(":name", name);
        if (!query.exec()) {
            qDebug() << "更新失败" << query.lastError().text();  // 执行异常处理[2](@ref)
            QMessageBox::critical(nullptr, "申请提示", "申请失败: " + memberModel->lastError().text());
            return;
        }
        // 信息提示框（带感叹号图标）
        QMessageBox::information(nullptr, "申请提示", "申请成功", QMessageBox::Ok);

    } else {
        QMessageBox::critical(nullptr, "申请提示", "该车不存在或不可使用: " + memberModel->lastError().text());
    }

}


void client::on_passTxtYes_clicked()
{
    QString old = pass;
    pass = ui->passTxt->text();
    // 参数化
    SQL = "UPDATE user SET "
          "upwd = :pass "
          "WHERE uname = :name";
    QSqlQuery query;
    query.prepare(SQL);
    query.bindValue(":pass", pass);
    query.bindValue(":name", name);
    if(!query.exec())
    {
        qDebug() << "更新失败：" << query.lastError().text();
        QMessageBox::warning(this,"修改失败","更新失败");
        ui->passTxt->setText(old);
        pass = old;
    }
    else
    {
        qDebug() << "更新成功，影响行数：" << query.numRowsAffected();
        QMessageBox::information(this,"更新成功","更新成功");
        ui->passTxt->setText(pass);
    }
}


void client::on_stickersTxtYes_clicked()
{
    if(vip != "VIP3" )
    {
        QMessageBox::warning(this,"错误提示","您的VIP等级暂不享有该功能！");
        return;
    }
    QString data = ui->stickersTxt->text();
    SQL = "insert into stickers(vip_name, vip_data) values ( :name, :data);";
    QSqlQuery query;
    query.prepare(SQL);
    query.bindValue(":name", name);
    query.bindValue(":data", data);
    if(!query.exec())
    {
        qDebug() << "更新失败：" << query.lastError().text();
        QMessageBox::warning(this,"添加失败","申请失败");
    }
    else
    {
        qDebug() << "更新成功，影响行数：" << query.numRowsAffected();
        QMessageBox::information(this,"申请成功","申请成功");
    }
}



void client::on_selectStickers_clicked()
{
    // 创建并配置模型
    kdcModel->setTable("stickers"); // 绑定到你的表名
    kdcModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置字段显示名称（与实际字段名无关，仅UI显示）
    kdcModel->setHeaderData(kdcModel->fieldIndex("vip_name"), Qt::Horizontal, "会员名称");
    kdcModel->setHeaderData(kdcModel->fieldIndex("vip_data"), Qt::Horizontal, "车贴内容");
    kdcModel->setHeaderData(kdcModel->fieldIndex("vip_state"), Qt::Horizontal, "任务进度");

    // 设置筛选条件
    // 合并条件，注意字符串值用单引号包裹
    SQL = QString(" vip_name = %1 ").arg(name);
    kdcModel->setFilter(SQL);


    error = kdcModel->lastError();

    if(!kdcModel->select()) { // 必须显式加载数据[2](@ref)
        QMessageBox::critical(nullptr, "错误", "数据加载失败: " + kdcModel->lastError().text());
        return;
    }

    // 将模型设置给meTableView
    ui->meTableView->setModel(kdcModel);
}

